package com.ftg.learn.framework.mybatis.javabase;

import com.mysql.cj.jdbc.Driver;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * 总配置
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/9/6 上午10:15
 */
public class Zong {

//    private E e1;

    private SqlSession session;

    // 单一职责

    // 生成数据源 Datasources
    public DataSource initDatasource(){
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("123456");
        mysqlDataSource.setURL("jdbc:mysql://localhost:3309/j2305");
        return mysqlDataSource;
    }

    //事务工厂
    public TransactionFactory initTransactionFactory(){
        TransactionFactory tran = new JdbcTransactionFactory();
        return tran;
    }

    //环境
    public Environment initEnvironment(){
        Environment e = new Environment("kjxlocalmysql1",initTransactionFactory(),initDatasource());
        return e;
    }

    //配置
    public Configuration initConfiguration(){
        Configuration configuration = new Configuration();

        //属性配置 打印你用到的所有sql信息
        configuration.setLogImpl(StdOutImpl.class);

        //构成环境
        configuration.setEnvironment(initEnvironment());

        //映射器 StudentMapper.class
        configuration.addMapper(StudentMapper.class);

        return configuration;
    }


    public SqlSession getSession(){
        SqlSessionFactoryBuilder gongRen = new SqlSessionFactoryBuilder();
        SqlSessionFactory gongChang = gongRen.build(initConfiguration());
        SqlSession chanPin = gongChang.openSession(true);
        return chanPin;
    }


    public void closeSession(SqlSession s){
        s.close();
    }

    public void commitSession(SqlSession s){
       s.commit();
    }

    public void rollBack(SqlSession s){
        s.rollback();
    }

    public <E> E getE1(Class<E> c1) {

        if(Objects.isNull(session)){
            session = getSession();
        }

        return  session.getMapper(c1);
    }
}
